from setting import BASE_URL,LOGIN_INFO
from loguru import logger
import requests
from utils.object_utils import cache


class Base(object):

    def __init__(self):
        pass

    # 实现URL的处理(拼接)
    def get_url(self,path,params=None):
        """
        将基础URL和接口路径给拼接起来，返回一个完整的URL
        :param path : 接口路径，比如 ：/admin/admin/create
        :param params : 查询参数 ，比如：?page=1&limit=20&sort=add_time&order=desc
        :return:  比如 ：http://121.196.13.152:8080/admin/admin/create
        """
        if params:
            full_url = BASE_URL + path + params
            return full_url
        return BASE_URL + path

    def http_request(self,method,url,data=None):
        """
        实现各种请求
        :return:
        """
        try:
            logger.info("cookie信息:{}".format(self.get_cookie()))
            response = requests.request(method,url,data=data,cookies=self.get_cookie())
            result = response.json()
            return result
        except Exception as e:
            logger.error("请求接口异常，请求方法:{},请求URL:{},错误信息:{}".format(method,url,e))
            raise e

    def set_cookie(self):
        """
        请求验证码接口，返回sessionid,保存到缓存中。
        :return:
        """
        verify_path = '/index.php?m=Home&c=User&a=verify'
        verify_url = self.get_url(verify_path)   # 验证码的URL
        verify_result = requests.get(verify_url)
        php_session = verify_result.cookies.get('PHPSESSID')    # 获取结果的cookie
        cookie = {'PHPSESSID': php_session}
        cache.set('cookie',cookie)

    def get_cookie(self):
        """
        获取cookie信息
        :return:
        """
        cookie = cache.get('cookie')
        if cookie:
            return cookie
        self.set_cookie()
        return cache.get('cookie')

    def get_veify(self):
        url = self.get_url('/index.php?m=Home&c=User&a=verify')
        verify_result = requests.get(url)
        return verify_result



    # 实现登录功能
    def login(self):
        """
        :return:
        """
        login_path = '/index.php?m=Home&c=User&a=do_login&t=0.879522389501395 '
        login_url = self.get_url(login_path)    # 登录的URL
        result = self.http_request('POST',login_url,LOGIN_INFO)     # 请求登录接口，返回json数据
        return result

    # 提现
    def tix(self):
        """
        提现测试
        :return:
        """
        self.login()
        self.get_veify()
        # path = '/index.php/home/User/withdrawals.html'
        url = self.get_url('/index.php/home/User/withdrawals.html')
        data = {'money':10,'bank_name':'中国招商银行','bank_card':"132100000000",'realname':'张三','verify_code':8888,'paypwd':123456}
        result = self.http_request('POST',url,data)

        logger.info("返回结果:{}".format(result))
        return result





if __name__ == '__main__':

    # 初始化对象
    base = Base()
    base.tix()